package com.wasu.sdk_ott.provider

import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.util.Log
import com.wasu.UILApplication
import com.wasu.constant.SYSTEM_CATEGORY_4K_IPDVB_HUIFANG
import com.wasu.constant.TAG
import com.wasu.database.keyvalue.KeyValueData

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 讯飞语音获得分组频道节目单数据
 * <p> 有要求，讯飞的分组频道，按照模式选择IPEPG或者IP直播管理系统，节目单，固定IP直播管理系统，鉴权，固定4K网关鉴权
 *
 * @author Created by zhangmz
 * @date on 2023/10/9
 */
class WasuSdkXunFeiProvider: WasuSdkModuleProvider() {

    override fun call(method: String, arg: String?, extras: Bundle?): Bundle? {
        Log.v(TAG, "WasuSdkXunFeiProvider call, method:$method; arg:$arg; extras:$extras")
        val bundle = Bundle()
        return when(method){
            LAUNCHER_GET_IP_BOUCH -> {
                bundle.putString("data", createRequest(PATH_WASU_SDK_IPLIVE_CHANNEL_GROUP, arrayOf("4", "", "1", "")))
                return bundle
            }
            LAUNCHER_GET_EPG_Q -> {
                val channelId = extras?.getString("contentId")
                if (channelId.isNullOrEmpty()){
                    Log.e(TAG, "WasuSdkXunFeiProvider call, query program channel id can not be null")
                    return bundle
                }
                // yyyy-MM-dd 时间格式
                val startDate = extras.getString("startDate")?: ""
                val endDate = extras.getString("endDate")?: ""
                Log.v(TAG, "WasuSdkXunFeiProvider call, query program, channelId:$channelId; startDate:$startDate; endDate:$endDate")
                val projection = arrayOf("0", SYSTEM_CATEGORY_4K_IPDVB_HUIFANG, "6", "2", "", "", channelId, startDate, endDate, "1")
                bundle.putString("data", createRequest(PATH_WASU_SDK_IPLIVE_PROGRAM, projection))
                return bundle
            }
            LAUNCHER_GET_CHANNEL_PURCHASED -> {
                val channelId = extras?.getString("contentId")
                Log.v(TAG, "WasuSdkXunFeiProvider call, query channel purchased, channelId:$channelId")
                if (channelId.isNullOrEmpty()){
                    Log.e(TAG, "WasuSdkXunFeiProvider call, query channel purchased channel id can not be null")
                    return bundle
                }
                val isPurchased = createRequest(PATH_WASU_SDK_IPLIVE_CHANNEL_PURCHASED, arrayOf(channelId, "", "huifang")).toBoolean()
                bundle.putBoolean("result", isPurchased)
                return bundle
            }
            LAUNCHER_VERSION -> {
                bundle.putString("LAUNCHER_VERSION","4K")
                bundle.putString("LAUNCHER_VERSION_STRING", "5.0")
                return bundle
            }
            LAUNCHER_SCENE_POS -> {
                var scenePos = "other"
                KeyValueData.instance().query("location")?.apply {
                    scenePos = when(value){
                        "1" -> "live"
                        "2" -> "vod"
                        else -> "other"
                    }
                }
                if (isDownGradeStatus()){
                    //降级状态
                    scenePos="degrade";
                }
                bundle.putString(LAUNCHER_SCENE_POS, scenePos)
                return bundle
            }
            else -> super.call(method, arg, extras)
        }
    }

    /**
     * 创建请求，实际调用的是父类query方法
     */
    private fun createRequest(path: String, projection: Array<out String>): String?{
        val uri = BASE_URI.buildUpon().appendPath(path).build()
        var cursor: Cursor? = null
        var result: String? = null
        try {
            cursor = query(uri, projection, null, null, null)
            if (cursor?.moveToNext() == false){
                Log.e(TAG, "WasuSdkXunFeiProvider, call, query cursor is null or not next")
                return null
            }
            val index = cursor?.getColumnIndex(RESULT_WASU_SDK_IPLIVE)?: -1
            if (index < 0){
                Log.e(TAG, "WasuSdkXunFeiProvider, call, query cursor column index:$index")
                return null
            }
            result = cursor?.getString(index)
            if (result.isNullOrEmpty()){
                Log.e(TAG, "WasuSdkXunFeiProvider, call, query result can not be null")
                return null
            }
        }catch (e: Exception){ e.printStackTrace() }
        finally {
            cursor?.close()
        }
        return result
    }
    private fun isDownGradeStatus(): Boolean {
        val sp = context!!.getSharedPreferences("downgrade", Context.MODE_MULTI_PROCESS)
        val downGradeStatus: String = sp.getString("downgradeStatus", "")!!
        // 是否处于一二级降级页面，降级页面不响应语音键
        val isDownGrade = "serviceDowngrading" == downGradeStatus ||"serviceDowngradingA" == downGradeStatus
                    || isEnsureForTopApp(UILApplication.getInstance().application)
        Log.v(TAG, "downGradeStatus:$downGradeStatus; 是否是降级状态 isDownGrade:$isDownGrade")

        return isDownGrade
    }
    fun isEnsureForTopApp(context: Context?): Boolean {
        return if (getDowngradeToSetting()) {
            true
        } else {
            makeSureTopWasuEnsureApp(context!!)
        }
    }
    fun getDowngradeToSetting(): Boolean {
        val model = KeyValueData.instance().query("downSetting") ?: return false
        Log.v("DownGradeUtil", "getDowngradeToSetting, getValue:" + model.value)
        return "true" == model.value
    }
    private val activeCountMethod = "ensureActiveCount"
    fun makeSureTopWasuEnsureApp(context: Context): Boolean {
        try {
            val provider = context.contentResolver
            val uri = Uri.parse("content://com.wasu.ensure.content.EnsureContentProvider")
            val bundle = provider.call(uri, activeCountMethod, null, null)
            Log.v("DownGradeUtil", "makeSureTopWasuEnsureApp, bundle:$bundle")
            if (bundle != null && bundle.containsKey(activeCountMethod)) {
                Log.v(
                    "DownGradeUtil",
                    "activeCount:" + bundle.getInt(activeCountMethod, -1)
                )
                return bundle.getInt(activeCountMethod, -1) > 0
            }
            return false
        } catch (e: java.lang.Exception) {
           Log.e(TAG, "error:$e")
            e.printStackTrace()
        }
        return false
    }
}